﻿using System;
using System.Collections.Generic;

namespace _36._有效的数独
{
    /// <summary>
    /// https://leetcode.cn/problems/valid-sudoku/
    /// </summary>
    public class Solution
    {
        public bool IsValidSudoku(char[][] board)
        {
            Dictionary<int, int>[] dictRow = new Dictionary<int, int>[9];
            Dictionary<int, int>[] dictCol = new Dictionary<int, int>[9];
            Dictionary<int, int>[] dictBox = new Dictionary<int, int>[9];

            for (int i = 0; i < 9; i++)
            {
                dictRow[i] = new Dictionary<int, int>();
                dictCol[i] = new Dictionary<int, int>();
                dictBox[i] = new Dictionary<int, int>();
            }


            for (int i = 0; i < 9; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    if (board[i][j] == '.') continue;

                    int num = int.Parse(board[i][j].ToString());

                    if (dictRow[i].ContainsKey(num))
                    {
                        return false;
                    }

                    if (dictCol[j].ContainsKey(num))
                    {
                        return false;
                    }

                    dictRow[i].Add(num, 1);
                    dictCol[j].Add(num, 1);

                    int box_index = (i / 3) * 3 + j / 3;// 0---8  共9小块，与i,j的关系。

                    if (dictBox[box_index].ContainsKey(num))
                    {
                        return false;
                    }

                    dictBox[box_index].Add(num, 1);
                }
            }
            return true;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            char[][] board = new char[][] {
                new char[]{'5', '3', '.', '.' ,'7','.', '.', '.', '.' },
                new char[]{'6', '.', '.', '1' ,'9','5', '.', '.', '.' },
                new char[]{'.', '9', '8', '.' ,'.','.', '.', '6', '.' },
                new char[]{'8', '.', '.', '.' ,'.','.', '.', '.', '.' },
                new char[]{'4', '.', '.', '.' ,'.','.', '.', '.', '.' },
                new char[]{'7', '.', '.', '.' ,'.','.', '.', '.', '.' },
                new char[]{'.', '6', '.', '.' ,'.','.', '2', '8', '.' },
                new char[]{'.', '.', '.', '4' ,'1','9', '.', '.', '5' },
                new char[]{'.', '.', '.', '.' ,'8','.', '.', '7', '9' },
            };
            //Dictionary<int, int> dict = new Dictionary<int, int>();


            Console.WriteLine(new Solution().IsValidSudoku(board));
        }
    }
}
